import { useCreation } from 'ahooks';
import React, { useMemo, useState } from 'react';
import { NodeProps } from 'reactflow';
import { useContextSelector } from 'use-context-selector';

import CollapsibleSection from '@/components/CollapsibleSection';
import { t } from '@/locales/i18n';
import { AppContext } from '@/pages/app/detail/context';
import { FlowNodeOutputTypeEnum, WorkflowIOValueTypeEnum } from '@/types/workflow/constant';
import { FlowNodeOutputItemType } from '@/types/workflow/io';
import { FlowNodeItemType } from '@/types/workflow/node';
import {
  formatEditorVariablePickerIcon,
  getAppChatConfig,
  getGuideModule,
} from '@/types/workflow/utils';
import { workflowSystemVariables } from '@/utils/app/utils';

import { WorkflowContext } from '../../context';

import NodeCard from './render/NodeCard';
import RenderOutput from './render/RenderOutput';

const NodeStart = ({ data, selected }: NodeProps<FlowNodeItemType>) => {
  const { nodeId, outputs } = data;
  const nodeList = useContextSelector(WorkflowContext, (v) => v.nodeList);
  const { appDetail } = useContextSelector(AppContext, (v) => v);

  const [expandedSections, setExpandedSections] = useState<Set<'output' | 'input' | 'params'>>(
    new Set(['input']),
  );

  const toggleSection = (section: 'output' | 'input' | 'params') => {
    setExpandedSections((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(section)) {
        newSet.delete(section);
      } else {
        newSet.add(section);
      }
      return newSet;
    });
  };

  const customGlobalVariables = useCreation(() => {
    const globalVariables = formatEditorVariablePickerIcon(
      getAppChatConfig({
        chatConfig: appDetail.chatConfig,
        systemConfigNode: getGuideModule(nodeList),
        isPublicFetch: true,
      })?.variables || [],
    );

    return globalVariables.map<FlowNodeOutputItemType>((item) => {
      return {
        id: item.key,
        type: FlowNodeOutputTypeEnum.static,
        key: item.key,
        required: item.required,
        valueType: item.valueType || WorkflowIOValueTypeEnum.any,
        label: t(item.label as any),
        valueDesc: item.valueDesc,
      };
    });
  }, [nodeList, appDetail.chatConfig, t]);

  const systemVariables = useMemo(
    () =>
      workflowSystemVariables.map((item) => ({
        id: item.key,
        type: FlowNodeOutputTypeEnum.static,
        key: item.key,
        required: item.required,
        valueType: item.valueType || WorkflowIOValueTypeEnum.any,
        label: t(item.label as any),
        valueDesc: item.valueDesc,
      })),
    [],
  );

  return (
    <NodeCard
      minW="315px"
      selected={selected}
      menuForbid={{
        copy: true,
        delete: true,
      }}
      {...data}
    >
      {/* <Container>
        <IOTitle text={t('common.Output')} />
        <RenderOutput nodeId={nodeId} flowOutputList={outputs} />
      </Container> */}

      <div className="flex flex-col gap-3 space-y-0">
        {customGlobalVariables.length > 0 && (
          <CollapsibleSection
            title={t('core.module.Variable')}
            subtitle={t('workflow.node.constom_config_desc')}
            isExpanded={expandedSections.has('params')}
            onToggle={() => toggleSection('params')}
            type="params"
          >
            <div className="nowheel max-h-[200px] overflow-y-auto px-2">
              <RenderOutput nodeId={nodeId} flowOutputList={customGlobalVariables} />
            </div>
          </CollapsibleSection>
        )}

        <CollapsibleSection
          title={t('workflow.node.global_variable_config')}
          subtitle={t('workflow.node.global_variable_config_desc')}
          isExpanded={expandedSections.has('input')}
          onToggle={() => toggleSection('input')}
          type="input"
        >
          <div className="nowheel max-h-[360px] overflow-y-auto px-2">
            <RenderOutput nodeId={nodeId} flowOutputList={systemVariables} />
          </div>
        </CollapsibleSection>

        <CollapsibleSection
          title={t('workflow.node.output')}
          subtitle={t('workflow.node.output_desc')}
          isExpanded={expandedSections.has('output')}
          onToggle={() => toggleSection('output')}
          type="output"
          className="pb-3"
        >
          <div className="max-h-[200px] overflow-y-auto px-2">
            <RenderOutput nodeId={nodeId} flowOutputList={outputs} />
          </div>
        </CollapsibleSection>
      </div>
    </NodeCard>
  );
};

export default React.memo(NodeStart);
